<?php

namespace app\shop\model\order;

use app\shop\model\BaseModel;
use app\shop\model\goods\GoodsModel;
use app\shop\model\goods\GoodsSkuModel;
use app\shop\service\OrderService;
use think\model\relation\BelongsTo;
use think\model\relation\HasOne;

class OrderDetailModel extends BaseModel
{
    protected $name = 'shop_order_detail';

    protected $type = [
        'discount_data' => 'json'
    ];

    protected $jsonAssoc = true;

    /**
     * 关联订单
     * @return BelongsTo
     * @noinspection PhpUnused
     */
    public function orderRelation(): BelongsTo
    {
        return $this->belongsTo(OrderModel::class, 'order_id', 'id');
    }

    /**
     * 关联售后
     * @return HasOne
     */
    public function refund(): HasOne
    {
        return $this->hasOne(OrderRefundModel::class, 'order_detail_id', 'id');
    }

    /**
     * 关联SKU
     * @return BelongsTo
     */
    public function sku(): BelongsTo
    {
        return $this->belongsTo(GoodsSkuModel::class, 'sku_id');
    }

    /**
     * 关联商品
     * @return BelongsTo
     */
    public function goods(): BelongsTo
    {
        return $this->belongsTo(GoodsModel::class, 'goods_id');
    }

    /**
     * 获取器：是否可申请售后
     * @return bool
     * @noinspection PhpUnused
     */
    public function getApplyRefundAttr(): bool
    {
        if ($this->orderRelation->receive_time <= 0) {
            return false;
        }
        if (!is_null($this->refund)) {
            return false;
        }
        $applyTime = (new OrderService())->getApplyRefundTime();

        return time() <= $this->orderRelation->receive_time + $applyTime;
    }
}
